from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.db.models import Q
from django.utils.translation import gettext_lazy as _

from oa.models import *
from tb3.utils import queryset_export_excel

admin.site.site_header = 'TR后台管理系统'
admin.site.site_title = 'TasteRoom'
admin.site.index_title = 'TR后台管理系统'


class SimpleModelAdmin(admin.ModelAdmin):
    view_on_site = False


class AutoUpdateUserModelAdmin(admin.ModelAdmin):
    view_on_site = False
    readonly_fields = ('created_by', 'updated_by')
    date_hierarchy = 'datetime_created'

    def save_model(self, request, instance, form, change):
        user = request.user
        instance = form.save(commit=False)
        if not change or not instance.created_by:
            instance.created_by = user
        instance.updated_by = user
        instance.save()
        form.save_m2m()
        return instance


@admin.register(UserLevel)
class UserLevelAdmin(SimpleModelAdmin):
    list_display = ['pk', 'level_code', 'level_name', 'desc']
    list_display_links = ['pk', 'level_code']
    search_fields = ['level_code', 'level_name', 'desc']


@admin.register(Company)
class CompanyAdmin(SimpleModelAdmin):
    list_display = ['pk', 'name']
    list_display_links = ['pk', 'name']
    search_fields = ['name']


@admin.register(WxUser)
class WxUserAdmin(UserAdmin):
    readonly_fields = (
        'last_login', 'date_joined', 'nick_name', 'city', 'province', 'country', 'avatar_url',
    )
    list_display = [
        'pk', 'username', 'full_name', 'nick_name', 'mobile',
        'is_staff', 'is_superuser', 'date_joined', 'last_login']
    list_display_links = ['pk', 'username', 'full_name', 'nick_name']
    search_fields = [
        'username', 'openid', 'email', 'mobile', 'full_name', 'first_name', 'last_name', 'nick_name']
    autocomplete_fields = ['user_level']
    list_filter = ('is_staff', 'is_superuser', 'groups')
    fieldsets = (
        (_('基础信息'), {'fields': ('username', 'password', 'openid')}),
        (_('个人信息'), {'fields': (
            'nick_name', 'first_name', 'last_name', 'full_name', 'avatar_url', 'gender', 'date_of_birth', 'desc'
        )}),
        (_('联络信息'), {'fields': ('mobile', 'email',)}),
        (_('地址信息'), {'fields': ('city', 'province', 'country')}),
        (_('分类信息'), {'fields': ('user_level',)}),
        (_('权限管理'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups')}),
        (_('登录信息'), {'fields': ('last_login', 'date_joined')}),
    )


@admin.register(Department)
class DepartmentAdmin(SimpleModelAdmin):
    list_display = ['pk', 'order_index', 'name', 'desc', 'department_type', 'is_active']
    list_display_links = ['pk', 'name', 'desc', 'is_active']
    search_fields = ['name', 'desc']
    list_filter = ['is_active', 'department_type']
    list_editable = ['order_index']


@admin.register(Staff)
class StaffAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'date_of_entry'
    list_display = [
        'pk', 'code', 'full_name', 'date_of_entry', 'gender', 'company', 'related_department', 'related_user',
        'position', 'mobile', 'desc']
    list_display_links = ['pk', 'code', 'full_name']
    search_fields = ['last_name', 'first_name', 'english_name', 'full_name', 'mobile']
    list_filter = ['gender', 'related_department', 'is_active', 'company']
    autocomplete_fields = ['related_user', 'company', 'related_department']


@admin.register(CustomerLevel)
class CustomerLevelAdmin(SimpleModelAdmin):
    list_display = ['pk', 'level_code', 'level_name', 'desc']
    list_display_links = ['pk', 'level_code']
    search_fields = ['level_code', 'level_name', 'desc']


class CustomerUserInline(admin.TabularInline):
    model = CustomerUser
    extra = 0
    fields = ['user']


@admin.register(Customer)
class CustomerAdmin(AutoUpdateUserModelAdmin):
    list_display = [
        'pk', 'nickname', 'full_name', 'contact', 'contact_mobile', 'department',
        'customer_level', 'related_salesman', 'need_statistic']
    list_display_links = ['pk', 'nickname']
    search_fields = ['nickname', 'full_name', 'contact', 'contact_mobile']
    list_filter = ['customer_level', 'related_salesman', 'need_statistic', 'department']
    list_editable = ['customer_level', 'related_salesman', 'department']
    autocomplete_fields = ['customer_level', 'related_salesman', 'department']
    inlines = [CustomerUserInline]


@admin.register(Equipment)
class EquipmentAdmin(AutoUpdateUserModelAdmin):
    list_display = ['pk', 'code', 'name', 'model', 'price', 'design_capacity', 'desc']
    list_display_links = ['pk', 'code', 'name', 'model']
    search_fields = ['code', 'name', 'model']


@admin.register(Warehouse)
class WarehouseAdmin(SimpleModelAdmin):
    list_display = ['pk', 'warehouse_type', 'name', 'address', 'contact', 'contact_mobile', 'desc']
    list_display_links = ['pk', 'name', ]
    search_fields = ['name', 'address', 'contact', 'contact_mobile']
    list_filter = ['warehouse_type']


@admin.register(MaterialCategory)
class MaterialCategoryAdmin(SimpleModelAdmin):
    list_display = ['pk', 'name', 'name_en', 'category_type', 'desc']
    list_display_links = ['pk', 'name']
    search_fields = ['name', 'name_en', 'desc']
    list_filter = ['category_type']


@admin.register(Material)
class MaterialAdmin(AutoUpdateUserModelAdmin):
    readonly_fields = ['created_by', 'updated_by', 'total_in', 'left_amount']
    date_hierarchy = None
    list_display = [
        'pk', 'code', 'name', 'name_en', 'batches_items',
        'total_in', 'left_amount', 'unit', 'material_category', 'desc', 'is_active']
    list_display_links = ['pk', 'code', 'name']
    search_fields = ['code', 'name', 'name_en', 'desc']
    list_filter = ['material_category', 'supplier', 'unit']
    filter_horizontal = ['supplier']

    def save_execl(self, request, queryset):
        filename = 'media/{0}_{1}.xls'.format('material', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        headers = [
            'ID', '物料代码', '名称', '英文名称', '归类', '入库总量', '剩余数量', '计量单位']
        columns = [
            'pk', 'code', 'name', 'name_en', 'material_category__name', 'total_in', 'left_amount', 'unit']
        return queryset_export_excel(queryset, headers, columns, filename)

    save_execl.short_description = "数据导出"

    actions = [save_execl]


@admin.register(Supplier)
class SupplierAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = None
    list_display = ['pk', 'name', 'contact', 'contact_mobile', 'company_name', 'desc']
    list_display_links = ['pk', 'name', 'contact']
    search_fields = ['name', 'contact', 'contact_mobile', 'company_name', 'desc']


@admin.register(PackageUnit)
class PackageUnitAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = None
    list_display = ['pk', 'display', 'amount', 'unit', 'is_material', 'is_product']
    list_display_links = ['pk', 'display']
    search_fields = ['display', 'amount', 'unit']
    list_filter = ['is_material', 'is_product']


@admin.register(MaterialBatch)
class MaterialBatchAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'expiration_date'
    readonly_fields = ('created_by', 'updated_by', 'total_in', 'left_amount', 'unit', 'unit_cost', 'unit_price')
    list_display = [
        'pk', 'code', 'material', 'package_unit', 'total_in', 'left_amount', 'unit', 'unit_price', 'unit_cost',
        'shelf_life', 'expiration_date', 'report', 'notes']
    list_display_links = ['pk', 'code', 'material']
    autocomplete_fields = ['material']
    list_filter = ['material__material_category', 'report_is_upload', 'package_unit', 'unit']
    search_fields = ['code', 'material__code', 'material__name', 'package_unit__amount']
    fieldsets = (
        (_('基础信息'), {
            'fields': (
                'code', 'material', 'package_unit',
                'production_date', 'shelf_life', 'expiration_date', 'notes')}),
        (_('质检信息'), {'fields': ('report',)}),
        (_('数量信息'), {'fields': ('total_in', 'left_amount', 'unit')}),
        (_('金额信息'), {'fields': ('unit_price', 'unit_cost')}),
    )

    def save_execl(self, request, queryset):
        filename = 'media/{0}_{1}.xls'.format('material_batch', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        headers = [
            'ID', '批次号', '物料代码', '原料名称', '归类', '入库总量', '剩余数量', '计量单位',
            '采购单价（元）', '单位成本（元）', '生产日期', '保质期/天', '到期日期']
        columns = [
            'pk', 'code', 'material__code', 'material__name', 'material__material_category__name',
            'total_in', 'left_amount', 'unit', 'unit_price', 'unit_cost',
            'production_date', 'shelf_life', 'expiration_date'
        ]
        queryset = queryset.filter(left_amount__gt=0).order_by('material__code')
        return queryset_export_excel(queryset, headers, columns, filename)

    save_execl.short_description = "数据导出"

    def update_price(self, request, queryset):
        for row in queryset:
            material_in = MaterialIn.objects.filter(material_batch_id=row.pk).order_by('pk').first()
            if material_in:
                material_in_record_datetime = material_in.related_order.record_datetime
            else:
                material_in_record_datetime = None
            material_out = MaterialOut.objects.filter(material_batch_id=row.pk).order_by('pk').first()
            if material_out:
                material_out_record_datetime = material_out.related_order.record_datetime
            else:
                material_out_record_datetime = None
            if material_in_record_datetime and material_out_record_datetime:
                if material_in_record_datetime < material_out_record_datetime:
                    material_in.save()
                else:
                    material_out.save()
            else:
                if material_in:
                    material_in.save()
                if material_out:
                    material_out.save()
    update_price.short_description = "更新价格"
    actions = [save_execl, update_price]


class MaterialPurchaseOrderItemInline(admin.TabularInline):
    model = MaterialPurchaseOrderItem
    extra = 0
    autocomplete_fields = ['material']
    readonly_fields = ['unit_cost']
    fields = ['material', 'package_unit', 'packs', 'price', 'unit_cost', 'exp_record_date']


class MoneyInOutInline(admin.TabularInline):
    model = MoneyInOut
    extra = 0
    fields = ['payment_date', 'amount', 'notes']


class MaterialInOrderInline(admin.TabularInline):
    model = MaterialInOrder
    extra = 0
    readonly_fields = ['code', 'material_ins', 'operator']
    fields = ['code', 'material_ins', 'operator']
    can_delete = False
    show_change_link = True


@admin.register(MaterialPurchaseOrder)
class MaterialPurchaseOrderAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'order_date'
    readonly_fields = (
        'created_by', 'updated_by', 'total_price', 'total_cost', 'total_payed', 'code', 'applied_by')
    list_display = [
        'pk', 'code', 'supplier', 'material_items', 'carriage_cost', 'total_discount',
        'total_cost', 'total_payed', 'file', 'file_extra', 'order_date', 'exp_record_date',
        'applied_by', 'confirmed_by', 'state', 'state_pay', 'is_confirmed']
    list_display_links = ['pk', 'code']
    autocomplete_fields = ['supplier', 'applied_by', 'confirmed_by']
    list_filter = ['supplier', 'state', 'state_pay', 'is_confirmed', 'applied_by', 'confirmed_by']
    search_fields = [
        'code',
        'materialpurchaseorderitem__material__name',
        'materialpurchaseorderitem__material__code',
        'materialinorder__code',
    ]
    inlines = [MaterialPurchaseOrderItemInline, MoneyInOutInline, MaterialInOrderInline]
    fieldsets = (
        (_('基础信息'), {
            'fields': (
                'code', 'applied_by', 'supplier', 'order_date', 'exp_record_date', 'file', 'file_extra', 'notes')
        }),
        (_('状态信息'), {
            'fields': ('state', 'state_pay', 'confirmed_by', 'is_confirmed')
        }),
        (_('金额信息'), {
            'fields': ('total_price', 'carriage_cost', 'total_discount', 'total_cost', 'total_payed')
        })
    )

    def auto_check(self, request, queryset):
        total_unconfirmed = queryset.filter(Q(is_confirmed=False) | Q(state__in=['1', '2']))
        for mpo in total_unconfirmed:
            it_c_all = MaterialPurchaseOrderItem.objects.filter(related_purchase_order=mpo).count()
            it_c_arr = MaterialPurchaseOrderItem.objects.filter(related_purchase_order=mpo).filter(
                is_arrived=True).count()
            if it_c_all:
                if it_c_all == it_c_arr:
                    mpo.is_confirmed = True
                    mpo.state = '3'
                    mpo.save()
        total_confirmed = queryset.filter(Q(is_confirmed=True) | Q(state__in=['3']))
        for mpo in total_confirmed:
            it_c_all = MaterialPurchaseOrderItem.objects.filter(related_purchase_order=mpo).count()
            it_c_arr = MaterialPurchaseOrderItem.objects.filter(related_purchase_order=mpo).filter(
                is_arrived=True).count()
            if it_c_all:
                if not it_c_all == it_c_arr:
                    mpo.is_confirmed = False
                    mpo.state = '1'
                    mpo.save()

    auto_check.short_description = "自动审核"

    def un_check(self, request, queryset):
        queryset.update(is_confirmed=False)

    un_check.short_description = "改为未核验"

    actions = [auto_check, un_check]


@admin.register(MaterialPurchaseOrderItem)
class MaterialPurchaseOrderItemAdmin(SimpleModelAdmin):
    list_display = [
        'pk', 'related_purchase_order', 'material', 'package_unit', 'packs', 'amount', 'amount_in',
        'unit_price', 'unit_cost',  'price', 'exp_record_date', 'is_arrived']
    list_display_links = ['pk', 'related_purchase_order', 'material', 'package_unit']
    autocomplete_fields = ['related_purchase_order', 'material', 'package_unit']
    list_filter = ['is_arrived', 'related_purchase_order', 'material', 'package_unit']


class MaterialInInline(admin.TabularInline):
    # form = MaterialInAdminForm
    model = MaterialIn
    readonly_fields = ['amount', 'unit']
    autocomplete_fields = ['material_batch']
    extra = 0
    fields = ['material_batch', 'warehouse', 'packs', 'amount', 'unit']


@admin.register(MaterialInOrder)
class MaterialInOrderAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'record_date'
    readonly_fields = ('created_by', 'updated_by', 'material_items', 'code', 'operator', 'record_datetime')
    list_display = [
        'pk', 'code', 'related_purchase_order', 'material_items', 'material_ins',
        'record_date', 'operator'
    ]
    list_display_links = ['pk', 'code',]
    autocomplete_fields = ['operator']
    list_filter = ['operator', 'related_purchase_order__supplier', 'related_purchase_order']
    search_fields = [
        'code',
        'related_purchase_order__code',
        'materialin__material_batch__material__code',
        'materialin__material_batch__material__name',
        'materialin__material_batch__code'
    ]
    inlines = [MaterialInInline]
    fieldsets = (
        (_('基础信息'), {'fields': (
            'code', 'related_purchase_order', 'record_date', 'operator', 'material_items'
        )}),
    )

    def update_material_in(self, request, queryset):
        for qs in queryset:
            mis = MaterialIn.objects.filter(related_order_id=qs.pk)
            for mi in mis:
                mi.save()

    update_material_in.short_description = "更新原料库存"

    actions = [update_material_in]


@admin.register(MaterialIn)
class MaterialInAdmin(AutoUpdateUserModelAdmin):
    readonly_fields = ['created_by', 'updated_by', 'related_order', 'amount', 'unit', 'unit_cost']
    list_display = [
        'pk', 'related_order', 'material_batch', 'amount', 'unit', 'warehouse', 'is_checked', 'is_confirmed']
    list_display_links = ['pk', 'material_batch']
    autocomplete_fields = ['material_batch', 'qualified']
    search_fields = ['material_batch__code', 'material_batch__material__code', 'material_batch__material__name']
    list_filter = ['is_checked', 'is_confirmed', 'warehouse']
    date_hierarchy = 'related_order__record_date'
    fieldsets = (
        (_('基础信息'), {'fields': ('related_order', 'material_batch', 'warehouse', 'packs')}),
        (_('数量信息'), {'fields': ('amount', 'unit')}),
        (_('质检信息'), {'fields': ('qualified', 'is_checked')}),
    )


@admin.register(ProductCategory)
class ProductCategoryAdmin(SimpleModelAdmin):
    list_display = ['pk', 'name', 'name_en', 'desc']
    list_display_links = ['pk', 'name']
    search_fields = ['name', 'name_en', 'desc']


class AwardInline(admin.TabularInline):
    model = Award
    extra = 0
    fields = ['name', 'award_date', 'award_level']


class ProductPackageInline(admin.TabularInline):
    model = ProductPackage
    extra = 0
    fields = ['code', 'name', 'package_unit', 'barcode', 'shelf_life']


@admin.register(ProductName)
class ProductNameAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = None
    list_display = [
        'pk', 'code', 'name', 'name_en', 'product_category',
        'abv', 'plato', 'ibu', 'color', 'materials',
        'is_oem', 'is_active', 'related_name', 'desc']
    list_display_links = ['pk', 'code', 'name']
    search_fields = ['code', 'name', 'name_en', 'desc']
    list_filter = ['is_active', 'product_category', 'is_oem']
    autocomplete_fields = ['product_category', 'related_name']
    inlines = [AwardInline, ProductPackageInline]
    fieldsets = (
        (_('基础信息'), {'fields': (
            'code', 'name', 'name_en', 'product_category', 'desc')}),
        (_('参数信息'), {'fields': (
            'abv', 'plato', 'ibu', 'color', 'materials', 'standard')}),
        (_('其他'), {'fields': (
            'is_oem', 'is_active', 'related_name')}),
    )


@admin.register(ProcessingCost)
class ProcessingCostAdmin(AutoUpdateUserModelAdmin):
    list_display = ['pk', 'name', 'cost', 'desc', 'is_active']
    list_display_links = ['pk', 'name']
    search_fields = ['name', 'desc']
    list_filter = ['is_active']


@admin.register(ProductBatch)
class ProductBatchAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'start_date'
    readonly_fields = ['created_by', 'updated_by', 'act_volume', 'product_yield', 'operations']
    list_display = [
        'pk', 'code', 'start_date', 'finish_date', 'delta_days', 'product_name', 'current_tank', 'est_volume', 'act_volume',
        'product_state', 'is_active', 'need_statistic', 'operations', 'notes']
    list_display_links = ['pk', 'code']
    list_filter = ['product_name', 'current_tank', 'product_state', 'processing_cost', 'is_active', 'need_statistic']
    autocomplete_fields = ['product_name', 'processing_cost', 'current_tank']
    search_fields = ['code', 'product_name__code', 'product_name__name']
    fieldsets = (
        (_('基础信息'), {'fields': (
            'code', 'product_state', 'product_name', 'current_tank', 'start_date', 'finish_date', 'is_active')}),
        (_('容量信息'), {'fields': (
            'total_volume', 'est_volume', 'act_volume', 'product_yield')}),
        (_('其他'), {'fields': (
            'processing_cost', 'report', 'notes', 'need_statistic', 'qr_code')}),
    )

    def auto_check(self, request, queryset):
        for pb in queryset:
            act_volume = pb.calculate_act_volume()
            pb.act_volume = act_volume
            pb.save()

    auto_check.short_description = "统计实际出酒量"

    def change_to_need_statistic(self, request, queryset):
        for pb in queryset:
            pb.need_statistic = True
            pb.save()

    change_to_need_statistic.short_description = "财务需要统计"

    def change_to_not_need_statistic(self, request, queryset):
        for pb in queryset:
            pb.need_statistic = False
            pb.save()

    change_to_not_need_statistic.short_description = "财务不需要统计"

    def create_qr_code_file(self, request, queryset):
        for pb in queryset:
            pb.make_qr_code()

    create_qr_code_file.short_description = "生成QR"

    actions = [auto_check, change_to_need_statistic, change_to_not_need_statistic, create_qr_code_file]


class LabelInline(admin.TabularInline):
    model = Label
    extra = 0
    fields = ['label_name', 'label_image', 'label_file', 'is_active']


class ProductImageInline(admin.TabularInline):
    model = ProductImage
    extra = 0
    fields = ['name', 'image', 'is_active']


class ProductPackageAttachInline(admin.TabularInline):
    model = ProductPackageAttach
    extra = 0
    fields = ['file_name', 'file', 'is_active']


@admin.register(ProductPackage)
class ProductPackageAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = None
    list_display = [
        'pk', 'code', 'name', 'product_name', 'package_unit', 'barcode',
        'safety_stock', 'current_stock', 'has_cost', 'has_sales_cost', 'is_draft', 'is_active']
    list_display_links = ['pk', 'code', 'name']
    autocomplete_fields = ['product_name']
    search_fields = ['name', 'product_name__code', 'product_name__name', 'package_unit__display', 'barcode', 'code']
    list_filter = [
        'is_draft', 'is_active', 'package_unit', 'product_name', 'product_name__product_category',
        'has_cost', 'has_sales_cost'
    ]
    inlines = [LabelInline, ProductImageInline, ProductPackageAttachInline]
    fieldsets = (
        (_('基础信息'), {'fields': (
            'code', 'name', 'product_name', 'licence', 'label_info',
            'barcode', 'shelf_life', 'is_draft', 'is_active')}),
        (_('包装信息'), {'fields': (
            'package_unit', 'width', 'height', 'weight', 'weight_net')}),
        (_('库存信息'), {
            'fields': ('safety_stock', 'current_stock'),
        }),
        (_('成本'), {
            'fields': ('reference_cost', 'sales_cost'),
        }),
    )

    # 更新成本
    def update_price(self, request, queryset):
        prices = ProductSalesPrice.objects.filter(
            sales_channel__name__in=['成本', '销售部门']
        ).values('package_group__code', 'price', 'sales_channel__name')
        price_dict = dict()
        for price in prices:
            price_dict['{}-{}'.format(price['package_group__code'], price['sales_channel__name'])] = price
        for pp in queryset:
            code = str(pp.code)
            if code[0] == 'B':
                p_code = '{}-24Z'.format(code)
                dv = 24
            elif code[0] == 'D':
                p_code = '{}-12Z'.format(code)
                dv = 12
            else:
                p_code = code
                dv = 1
            pr_reference_cost = price_dict.get('{}-{}'.format(p_code, '成本'))
            if pr_reference_cost:
                reference_cost = pr_reference_cost.get('price') / dv
                pp.reference_cost = reference_cost
            else:
                pp.reference_cost = 0
            pr_sales_cost = price_dict.get('{}-{}'.format(p_code, '销售部门'))
            if pr_sales_cost:
                sales_cost = pr_sales_cost.get('price') / dv
                pp.sales_cost = sales_cost
            else:
                pp.sales_cost = 0
            pp.save()

    update_price.short_description = "更新成本"

    actions = [update_price]


@admin.register(BrewBatch)
class BrewBatchAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'brew_start'
    list_display = [
        'pk', 'code', 'product_batch', 'brew_start', 'materials', 'operator', 'report', 'is_confirmed']
    list_display_links = ['pk', 'code']
    autocomplete_fields = ['product_batch', 'operator']
    search_fields = ['code', 'product_batch__code', 'product_batch__product_name__name']
    list_filter = ['is_confirmed', 'operator', 'file_is_upload']
    readonly_fields = ('created_by', 'updated_by', 'is_active')
    fieldsets = (
        (_('基础信息'), {'fields': (
            'code', 'product_batch', 'brew_start', 'brew_end', 'operator', 'report', 'is_confirmed')}),
        (_('其他信息'), {'fields': ('created_by', 'updated_by')}),
    )


@admin.register(PackBatch)
class PackBatchAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'pack_start'
    readonly_fields = ('created_by', 'updated_by', 'left_amount')
    list_display = [
        'pk', 'code', 'product_name', 'product_batch', 'package_unit',
        'pack_start', 'pack_end', 'last_batch', 'pack_amount', 'left_amount', 'materials',
        'record_file', 'operator', 'qualified', 'is_confirmed', 'is_checked']
    list_display_links = ['pk', 'code']
    autocomplete_fields = ['product_batch', 'operator', 'qualified', 'product_name']
    search_fields = [
        'code', 'product_package__product_name__name', 'product_name__name', 'product_package__package_unit__display']
    list_filter = [
        'is_checked', 'is_confirmed', 'operator', 'qualified', 'file_is_upload',
        'product_batch', 'product_name', 'last_batch']
    fieldsets = (
        (_('基本信息'), {'fields': (
            'code', 'product_batch', 'product_name', 'package_unit', 'product_package',
            'pack_start', 'pack_end', 'last_batch',
            'pack_amount', 'is_confirmed', 'notes', 'record_file', 'operator')}),
        (_('质检信息'), {'fields': ('report', 'qualified', )}),
    )


@admin.register(ProcessRecord)
class ProcessRecordAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'process_start'
    list_display = [
        'pk', 'code', 'process_type', 'product_batch', 'process_start', 'process_end', 'materials',
        'current_tank', 'operator', 'file']
    list_display_links = ['pk', 'code']
    search_fields = [
        'code', 'product_batch__code', 'product_batch__product_name__code', 'product_batch__product_name__name']
    list_filter = ['current_tank', 'operator', 'file_is_upload', 'process_type']
    autocomplete_fields = ['operator', 'product_batch']


@admin.register(EquipmentUsageRecord)
class EquipmentUsageRecordAdmin(SimpleModelAdmin):
    list_display = [
        'pk', 'equipment', 'product_batch', 'process_record', 'datetime_start']
    list_display_links = ['pk', 'equipment', 'product_batch']
    list_filter = ['equipment']
    autocomplete_fields = ['equipment', 'product_batch']


class PackageItemInline(admin.TabularInline):
    model = PackageItem
    extra = 0
    fields = ['product_package', 'amount']
    autocomplete_fields = ['product_package']


class MaterialItemInline(admin.TabularInline):
    model = MaterialItem
    extra = 0
    fields = ['material', 'amount']
    # autocomplete_fields = ['material']


@admin.register(PackageGroup)
class PackageGroupAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = None
    readonly_fields = ('created_by', 'updated_by', 'current_stock', 'packs', 'sales_cost', 'reference_cost')
    list_display = [
        'pk', 'code', 'name', 'total_amount',
        'length', 'width', 'height', 'weight', 'weight_net',
        'reference_price', 'sales_cost', 'reference_cost', 'barcode', 'packs', 'safety_stock',
        'is_active', 'is_show']
    list_display_links = ['pk', 'name']
    search_fields = [
        'name', 'barcode', 'code', 'packageitem__product_package__product_name__code',
        'packageitem__product_package__product_name__name', 'packageitem__product_package__barcode']
    list_filter = [
        'is_active', 'packageitem__product_package', 'packageitem__product_package__product_name',
        'packageitem__product_package__package_unit', 'total_amount', 'is_show',
        'has_cost', 'has_sales_cost'
    ]
    inlines = [PackageItemInline, MaterialItemInline]
    fieldsets = (
        (_('基础信息'), {'fields': (
            'code', 'name', 'total_amount', 'reference_price', 'sales_cost',
            'reference_cost', 'barcode', 'is_active', 'is_show')}),
        (_('包装信息'), {'fields': (
            'length', 'width', 'height', 'weight', 'weight_net')}),
        (_('库存信息'), {
            'fields': ('safety_stock', 'current_stock'),
        }),
    )

    def save_execl(self, request, queryset):
        filename = 'media/{0}_{1}.xls'.format('package_group_detail', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        headers = [
            'ID', '内部编码', '名称', '数量', '条码', '长度/mm', '宽度/mm', '高度/mm', '毛重/kg', '净含量/L']
        columns = [
            'pk', 'code', 'name', 'total_amount', 'barcode', 'length', 'width', 'height', 'weight', 'weight_net']
        return queryset_export_excel(queryset, headers, columns, filename)

    save_execl.short_description = "数据导出"

    # 更新成本和利润
    def update_profits(self, request, queryset):
        for qs in queryset:
            # 生产成本
            reference_cost = ProductSalesPrice.objects.filter(
                sales_channel__sales_channel_type=4, package_group_id=qs.pk
            ).order_by('-datetime_created').values('price').first()
            if reference_cost:
                qs.reference_cost = reference_cost['price']
                qs.has_cost = True
            else:
                qs.reference_cost = 0
                qs.has_cost = False
            # 出厂成本，销售部门结算价
            sales_cost = ProductSalesPrice.objects.filter(
                sales_channel__name='销售部门', package_group_id=qs.pk
            ).order_by('-datetime_created').values('price').first()
            if sales_cost:
                qs.sales_cost = sales_cost['price']
                qs.has_sales_cost = True
            else:
                qs.sales_cost = 0
                qs.has_sales_cost = False
            qs.save()

    update_profits.short_description = "更新成本"

    # 生成默认价格
    def create_default_prices(self, request, queryset):
        scs = SalesChannel.objects.all().values('pk')
        sales_channels = list()
        for sc in scs:
            sales_channels.append(sc['pk'])
        for qs in queryset:
            for sales_channel_id in sales_channels:
                ProductSalesPrice.objects.get_or_create(
                    sales_channel_id=sales_channel_id,
                    package_group_id=qs.pk,
                    defaults={'price': 0, 'is_active': False}
                )

    create_default_prices.short_description = "生成默认价格"

    actions = [save_execl, update_profits, create_default_prices]


class MaterialOutInline(admin.TabularInline):
    model = MaterialOut
    extra = 0
    fields = ['warehouse', 'material_batch', 'amount']
    autocomplete_fields = ['material_batch']


@admin.register(MaterialOutOrder)
class MaterialOutOrderAdmin(AutoUpdateUserModelAdmin):
    list_display = [
        'pk', 'code', 'record_date', 'material_out_type', 'operator', 'material_items',
        'brew_batch', 'pack_batch', 'process_record', 'group_batch']
    list_display_links = ['pk', 'code']
    search_fields = [
        'code', 'materialout__material_batch__code', 'materialout__material__code', 'materialout__material__name',
    ]
    readonly_fields = ('created_by', 'updated_by', 'product_batch', 'code', 'operator')
    list_filter = [
        'is_confirmed', 'material_out_type', 'operator', 'product_batch',
        'brew_batch', 'pack_batch', 'process_record', 'group_batch']
    inlines = [MaterialOutInline]
    autocomplete_fields = ['brew_batch', 'process_record', 'pack_batch', 'group_batch']
    fieldsets = (
        (_('基本信息'), {'fields': (
            'code', 'record_date', 'material_out_type', 'operator', 'is_confirmed', 'notes')}),
        (_('关联批次'), {'fields': (
            'product_batch', 'brew_batch', 'process_record', 'pack_batch', 'group_batch')}),
    )


@admin.register(MaterialOut)
class MaterialOutAdmin(AutoUpdateUserModelAdmin):
    list_display = [
        'pk', 'material_batch', 'amount', 'is_confirmed']
    list_display_links = ['pk', 'material_batch']
    search_fields = [
        'material_batch__code', 'material_batch__material__code', 'material_batch__material__name',
    ]
    list_filter = ['is_confirmed', 'material_batch__material__material_category']


@admin.register(DocumentType)
class DocumentTypeAdmin(SimpleModelAdmin):
    list_display = ['pk', 'name', 'desc']
    list_display_links = ['pk', 'name', 'desc']
    search_fields = ['name', 'desc']


@admin.register(Document)
class DocumentAdmin(AutoUpdateUserModelAdmin):
    readonly_fields = ['link']
    list_display = ['pk', 'name', 'version', 'link', 'document_type', 'related_department', 'operator', 'is_confirmed']
    list_display_links = ['pk', 'name']
    search_fields = ['name']
    list_filter = ['document_type', 'related_department', 'operator', 'is_confirmed']
    autocomplete_fields = ['operator', 'related_department', 'document_type']


class PackBatchItemInline(admin.TabularInline):
    model = PackBatchItem
    extra = 0
    autocomplete_fields = ['pack_batch']
    fields = ['pack_batch', 'amount']


@admin.register(GroupBatch)
class GroupBatchAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'group_start'
    readonly_fields = ('created_by', 'updated_by', 'left_amount')
    list_display = [
        'pk', 'code', 'package_group', 'group_start', 'group_end', 'amount', 'left_amount',
        'materials', 'operator', 'is_active']
    list_display_links = ['pk', 'code']
    search_fields = [
        'code', 'package_group__name']
    list_filter = ['is_active', 'operator']
    autocomplete_fields = ['package_group', 'operator']
    inlines = [PackBatchItemInline]
    fieldsets = (
        (_('基本信息'), {'fields': (
            'code', 'group_start', 'group_end', 'package_group', 'operator', 'amount', 'record_file')}),
    )


class FeedbackAttachmentInline(admin.TabularInline):
    model = FeedbackAttachment
    extra = 0
    fields = ['file']


@admin.register(FeedBackCategory)
class FeedBackCategoryAdmin(SimpleModelAdmin):
    list_display = ['pk', 'name', 'desc']
    list_display_links = ['pk', 'name', 'desc']
    search_fields = ['name', 'desc']


@admin.register(FeedBack)
class FeedBackAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'feedback_date'
    list_display = [
        'pk', 'feedback_date', 'feedback_category', 'amount', 'feedback_type', 'level', 'channels',
        'product_package', 'content', 'reply_content', 'reply_date',
    ]
    list_display_links = ['pk', 'feedback_date', 'content']
    search_fields = ['content', 'reply_content']
    list_filter = ['product_name', 'product_package', 'package_group', 'feedback_category']
    fieldsets = (
        (_('反馈信息'), {'fields': (
            'related_customer', 'feedback_date', 'feedback_category', 'feedback_type', 'channels', 'content')}),
        (_('产品信息'), {'fields': (
            'amount', 'product_name', 'product_package', 'package_group', 'pack_batch')}),
        (_('反馈处理'), {'fields': (
            'level', 'reply_date', 'reply_by', 'reply_content', 'process', 'cost')}),
    )
    autocomplete_fields = [
        'related_customer', 'reply_by', 'product_name', 'product_package', 'pack_batch', 'package_group']
    inlines = [FeedbackAttachmentInline]
    list_editable = ['feedback_category']

    def save_execl(self, request, queryset):
        filename = 'media/{0}_{1}.xls'.format('feedback_detail', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        headers = [
            'ID', '日期', '问题归类', '反馈渠道', '产品包装', '数量', '反馈内容', ]
        columns = [
            'pk', 'feedback_date', 'feedback_category__name',
            'channels', 'product_package__name', 'amount', 'content']
        return queryset_export_excel(queryset, headers, columns, filename)

    save_execl.short_description = "数据导出"

    actions = [save_execl]


@admin.register(FermentMonitor)
class FermentMonitorAdmin(AutoUpdateUserModelAdmin):
    date_hierarchy = 'recorded_at'
    readonly_fields = ['created_by', 'updated_by', 'sg', 'plato', 'recorded_by']
    list_display = [
        'pk', 'recorded_at', 'product_batch', 'sg', 'plato', 'ph', 't_real', 't_set', 'bar',
        'diacetyl', 'slag', 'cell_mml', 'cell_pd', 'file', 'notes'
    ]
    list_display_links = ['pk', 'recorded_at', 'product_batch']
    autocomplete_fields = ['product_batch']
    search_fields = ['product_batch__code']
    list_filter = ['recorded_by', 'product_batch']
    fieldsets = (
        (_('基本信息'), {'fields': (
            'product_batch', 'recorded_at', 'recorded_by')}),
        (_('参数'), {'fields': (
            'sg_plato', 'sg', 'plato', 'ph', 't_real', 't_set', 'bar', 'diacetyl', 'slag',
            'cell_mml', 'cell_pd', 'file')}),
        (_('备注'), {'fields': ('notes', 'created_by', 'updated_by')}),
    )


@admin.register(MaterialBatchStorage)
class MaterialBatchStorageAdmin(SimpleModelAdmin):
    date_hierarchy = 'record_datetime'
    readonly_fields = []
    list_display = [
        'pk', 'material_batch', 'warehouse', 'material_in', 'material_out', 'total_in', 'left_amount',
        'cw_total_in', 'cw_left_amount', 'unit_price', 'unit_cost', 'record_datetime']
    list_filter = ['warehouse', 'material_batch', 'record_datetime']
    search_fields = ['material_batch__code', 'material_batch__material__code', 'material_batch__material__name']
    autocomplete_fields = ['material_batch', 'warehouse', 'material_in', 'material_out']


@admin.register(SalesChannel)
class SalesChannelAdmin(AutoUpdateUserModelAdmin):
    list_display = ['pk', 'name', 'sales_channel_type', 'is_public']
    list_filter = ['sales_channel_type']
    search_fields = ['name', 'sales_channel_type']


@admin.register(ProductSalesPrice)
class ProductSalesPriceAdmin(AutoUpdateUserModelAdmin):
    list_display = ['pk', 'package_group', 'sales_channel', 'price', 'notes', 'is_active', 'is_public']
    list_display_links = ['pk', 'package_group']
    list_filter = [
        'package_group', 'sales_channel', 'package_group__total_amount', 'sales_channel__sales_channel_type',
        'package_group__packageitem__product_package__package_unit', 'is_active']
    search_fields = ['package_group__code', 'package_group__name']
    autocomplete_fields = ['package_group', 'sales_channel']
    list_editable = ['price']

    def to_public(self, request, queryset):
        for pb in queryset:
            pb.is_public = True
            pb.save()

    to_public.short_description = "公开数据"

    def to_private(self, request, queryset):
        for pb in queryset:
            pb.is_public = False
            pb.save()

    to_private.short_description = "不公开数据"

    def to_active(self, request, queryset):
        for pb in queryset:
            if pb.price:
                pb.is_active = True
                pb.save()

    to_active.short_description = "转为有效"

    actions = [to_public, to_private, to_active]
